package com.ruoyi.project.rate.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.framework.web.service.CrudService;
import com.ruoyi.project.rate.Constants;
import com.ruoyi.project.rate.domain.Kh;
import com.ruoyi.project.rate.domain.KhRule;
import com.ruoyi.project.rate.domain.KhTrack;
import com.ruoyi.project.rate.mapper.KhMapper;
import com.ruoyi.project.system.dict.service.IDictDataService;

@Service
public class KhService extends CrudService<KhMapper, Kh> {
	@Autowired
	private KhMapper khMapper;
	@Autowired
	private KhTrackService khTrackService;
	@Autowired
	private KhRuleService khRuleService;
	@Autowired
	private IDictDataService dictDataService;
	
	@Transactional(readOnly = false)
	public int save(Kh kh, List<KhRule> khRuleList) {
		// 查询数据库中已有的数据，准备删除
		Map<String, KhRule> ruleMap = new HashMap<>();

		if (StringUtils.isNotBlank(kh.getId())) {
			KhRule khRule = new KhRule();
			khRule.setKh(kh);
			List<KhRule> rules = this.khRuleService.findList(khRule);
			for (KhRule r : rules) {
				ruleMap.put(r.getId(), r);
			}
		}

		// kh.setStatus(Constants.KH_STATUS_DRAFT);
		int i = super.save(kh);

		for (KhRule rule : khRuleList) {
			rule.setKh(kh);
			this.khRuleService.save(rule);
			ruleMap.remove(rule.getId());
		}

		for (KhRule rule : ruleMap.values()) {
			this.khRuleService.delete(rule);
		}

		return i;
	}

	/**
	 * 提交审核
	 * @param kh
	 * @return
	 */
	@Transactional(readOnly = false)
	public int submitToCheck(Kh kh) {
		kh.setStatus(Constants.KH_STATUS_KHZ);
		
		int i = this.khMapper.updateStatus(kh);
		
		this.addTrack(kh, "提交考核组审批", "提交考核组审批成功");
		return i;
	}
	/**
	 * 批量提交审核
	 * @param kh
	 * @param ids
	 * @return
	 */
	@Transactional(readOnly = false)
	public int batchSubmitToCheck(Kh kh, String ids) {
		int checkedCount = 0;
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			Kh _kh = this.get(id);
			if (_kh == null) {
				continue;
			}
			
			if (!StringUtils.equalsAny(_kh.getStatus(),
					Constants.KH_STATUS_DRAFT,
					Constants.KH_STATUS_REJECTED)) {
				continue;
			}
			
			this.submitToCheck(_kh);
			checkedCount++;
		}
		
		return checkedCount;
	}
	
	@Transactional(readOnly = false)
	public void submitCheck(Kh kh) {
		String pageFlag = kh.getPageFlag();
		
		String operation = dictDataService.selectDictLabel(
				Constants.KH_STATUS, pageFlag);
		if (StringUtils.isBlank(operation)) {
			throw new RuntimeException("error operation[submitCheck]");
		}
		
		String next = null;
		if (Constants.KH_STATUS_KHZ.equals(pageFlag)) {
			next = Constants.KH_STATUS_FGLD;
		} else if (Constants.KH_STATUS_FGLD.equals(pageFlag)) {
			next = Constants.KH_STATUS_HZ;
		} else if (Constants.KH_STATUS_HZ.equals(pageFlag)) {
			next = Constants.KH_STATUS_APPROVED;
		}
		if (StringUtils.isBlank(next)) {
			throw new RuntimeException("error next status[submitCheck]");
		}
		
		if (Constants.KH_STATUS_APPROVED.equals(kh.getCheckResult())) {
			kh.setStatus(next);
		} else {
			kh.setStatus(Constants.KH_STATUS_REJECTED);
		}
		
		kh.setCheckTime(new Date());
		this.khMapper.submitCheck(kh);
		
		if (Constants.PAGE_FLAG_KHZ.equals(pageFlag)) {
			this.khMapper.updateFgldChecker(kh);
		}
		
		// 记录轨迹
		String result = Constants.KH_STATUS_APPROVED.equals(kh.getCheckResult()) ? "审核通过" : "审核不通过";
		this.addTrack(kh, operation, result + "，审核意见：" + kh.getCheckDesc());
	}
	
	/**
	 * 批量审核
	 * @param kh
	 * @param ids
	 * @return
	 */
	@Transactional(readOnly = false)
	public int batchSubmitCheck(Kh kh, String ids) {
		int checkedCount = 0;
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			Kh _kh = this.get(id);
			if (_kh == null) {
				continue;
			}
			
			if (!StringUtils.equals(_kh.getStatus(), kh.getPageFlag())) {
				continue;
			}
			
			_kh.setPageFlag(kh.getPageFlag());
			_kh.setFgldChecker(kh.getFgldChecker());
			_kh.setCheckResult(kh.getCheckResult());
			if (Constants.KH_STATUS_APPROVED.equals(_kh.getCheckResult())) {
				_kh.setCheckDesc("通过");
			} else {
				_kh.setCheckDesc("拒绝");
			}
			
			this.submitCheck(_kh);
			checkedCount++;
		}
		
		return checkedCount;
	}

	@Transactional(readOnly = false)
	public void cancelCheck(Kh kh) {
		String pageFlag = kh.getPageFlag();
		String operation = dictDataService.selectDictLabel(Constants.KH_STATUS, pageFlag);
		if (StringUtils.isBlank(operation)) {
			throw new RuntimeException("error operation[cancelCheck]");
		}
		operation += "-撤销";

		Kh exists = this.get(kh);
		if (exists == null) {
			throw new RuntimeException("查询不到记录.");
		}
		String currentStatus = exists.getStatus();
		boolean canCancelCheck = false;

		// 校验是否可撤回审核
		if (Constants.KH_STATUS_HZ.equals(pageFlag)
				&& Constants.KH_STATUS_APPROVED.equals(currentStatus)) {
			canCancelCheck = true;
		} else if (Constants.KH_STATUS_FGLD.equals(pageFlag)
				&& Constants.KH_STATUS_HZ.equals(currentStatus)) {
			canCancelCheck = true;
		} else if (Constants.KH_STATUS_KHZ.equals(pageFlag)
				&& Constants.KH_STATUS_FGLD.equals(currentStatus)) {
			canCancelCheck = true;
		}

		if (!canCancelCheck) {
			throw new RuntimeException("当前状态不允许撤回审核.");
		}

		kh.setStatus(pageFlag);
		this.khMapper.updateStatus(kh);

		// 记录轨迹
		this.addTrack(kh, operation, null);
	}
	
	/**
     * 撤回报表
     */
    @Transactional(readOnly = false)
    public void cancel(Kh kh) {
    	String operation = null;
    	String currentStatus = kh.getStatus();
    	boolean canCancelRec = false;
    	
		if (Constants.KH_STATUS_KHZ.equals(currentStatus)) {
			canCancelRec = true;
			operation = "撤回";
    		kh.setStatus(Constants.KH_STATUS_DRAFT);
		}
    	
    	if (!canCancelRec) {
    		throw new RuntimeException("不允许当前操作！");
    	}
    	
    	this.khMapper.updateStatus(kh); // 更新状态
    	
    	// 记录轨迹
    	this.addTrack(kh, operation, "撤回成功");
    }
    @Transactional(readOnly = false)
	public int batchCancel(Kh kh, String ids) {
		int checkedCount = 0;
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			Kh _kh = this.get(id);
			if (_kh == null) {
				continue;
			}
			
			if (!StringUtils.equals(_kh.getStatus(), Constants.KH_STATUS_KHZ)) {
				continue;
			}
			
			this.cancel(_kh);
			checkedCount++;
		}
		
		return checkedCount;
	}
    
	private void addTrack(Kh kh, String operation, String remark) {
		KhTrack track = new KhTrack();
		track.setKh(kh);
		track.setOperation(operation);
		track.setRemark(remark);
		track.setCurrentStatus(kh.getStatus());
		this.khTrackService.save(track);
	}
	
	@Transactional(readOnly = false)
	public int updateStatus(Kh kh) {
		return this.khMapper.updateStatus(kh);
	}
}
